<template>
  <el-page-header
    title="发布包管理中心"
    :icon="null"
    style="font-size: 16px; border-bottom: 1px solid #ddd"
  >
    <template #extra>
      <el-button @click="logout">退出登录</el-button>
    </template>
  </el-page-header>
  <div class="main" style="margin-top: 20px">
    <div class="top">
      <el-input
        :prefix-icon="Search"
        v-model="search.name"
        @input="searchItems"
        style="width: 200px; margin-right: 16px"
      ></el-input>
      <el-select v-model="search.type" @change="queryItems">
        <el-option
          v-for="r in options"
          :key="r.value"
          :value="r.value"
          :label="r.label"
        ></el-option>
      </el-select>
      <el-button @click="uploadFile" style="margin-left: 16px">上传包</el-button>
      <el-button @click="batchDelete" style="margin-left: 16px">批量删除</el-button>
    </div>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      style="width: 100%; margin-top: 16px"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="名称" width="300" />
      <el-table-column prop="type" label="类型" width="180">
        <template #default="{ row }">
          <span>{{ typeHandler(row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="version" label="版本" width="180" />
      <el-table-column prop="uploadtime" label="上传时间" width="240">
        <template #default="{ row }">
          <span>{{ timeHandler(row.uploadtime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="operation" label="操作">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="downloadItem(row)">下载</el-button>
          <el-button link type="primary" size="small" @click="edit(row)">编辑</el-button>
          <el-button link type="primary" size="small" @click="delItem(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="search.page"
      v-model:page-size="search.itemsPerPage"
      background
      :page-sizes="[10, 20, 30, 40]"
      :pager-count="10"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="queryItems"
      @current-change="queryItems"
    />
    <el-dialog v-model="dialogVisible">
      <el-form>
        <el-form-item label="类型" key="0">
          <el-select v-model="form.type">
            <el-option
              v-for="r in options"
              :key="r.value"
              :value="r.value"
              :label="r.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本">
          <el-input v-model="form.version"></el-input>
        </el-form-item>
        <el-form-item label="文件" v-if="mode === 'add'">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="/api/upload"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            v-model:file-list="fileList"
          >
            <el-button type="primary">选取文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" :rows="2" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import router from '@/router'
import { removeToken } from '@/utils/token'
import { onMounted, reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { upload, update, del, batchDel, download, query } from '@/api/gov'
import { debounce } from 'lodash'

const logout = () => {
  removeToken()
  router.replace({ name: 'Login' })
}
const uploadRef = ref()
const dialogVisible = ref(false)
const tableData = ref([])
const total = ref(0)
const mode = ref('add')
const multiItems = ref([])
const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  const file = files[0]
  uploadRef.value.handleStart(file)
}
const options = [
  { value: 0, label: '项目包' },
  { value: 1, label: '前端发布包' },
  { value: 2, label: '后端发布包' },
  { value: 3, label: '前端资源库' },
  { value: 4, label: '后端端资源库' },
  { value: 5, label: '全部' },
]
const typeHandler = (type) => {
  const option = options.find((item) => item.value == type)
  return option && option.label
}
const timeHandler = (timestamp) => {
  // 此处时间戳以毫秒为单位
  let date = new Date(parseInt(timestamp))
  let Year = date.getFullYear()
  let Moth = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  let Day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  let Hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  let Minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  let Sechond = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  let GMT = Year + '-' + Moth + '-' + Day + '   ' + Hour + ':' + Minute + ':' + Sechond
  return GMT
}
const fileList = ref([])
const form = ref({
  type: 0,
  version: 'v1.0.0',
  description: '',
})
const search = reactive({
  name: '',
  type: '',
  page: 1,
  itemsPerPage: 10,
})
const searchItems = (value) => {
  debounce(() => {
    queryItems()
  }, 1000)()
}
const uploadFile = () => {
  dialogVisible.value = true
  form.value = {
    type: 0,
    version: 'v1.0.0',
    description: '',
  }
  mode.value = 'add'
}
const submitForm = () => {
  if (mode.value === 'edit') {
    editConfirm()
    return
  }
  const file = fileList.value[0]
  const formData = new FormData()
  formData.append('type', form.value.type)
  formData.append('version', form.value.version)
  formData.append('description', form.value.description)
  formData.append('name', file.name)
  formData.append('file', file.raw)
  formData.append('id', file.uid)
  upload(formData).then((rsp) => {
    dialogVisible.value = false
    fileList.value = []
    queryItems()
  })
}

const editConfirm = () => {
  update(form.value).then((rsp) => {
    queryItems()
    dialogVisible.value = false
  })
}

const queryItems = () => {
  query(search).then((rsp) => {
    if (rsp.code === 200) {
      const data = rsp.data
      tableData.value = data.list
      total.value = data.total
    }
  })
}

const edit = (row) => {
  mode.value = 'edit'
  form.value = row
  dialogVisible.value = true
}
const delItem = (row) => {
  del({ id: row.id, name: row.name }).then((rsp) => {
    if (rsp.code === 200) {
      queryItems()
    }
  })
}
const downloadItem = (row) => {
  download({ uploadtime: row.uploadtime, name: row.name }).then((rsp) => {
    //1 生成文件的 blob 对象 // 指定转换成blob的类型 => 使用 Blob 创建一个指向类型化数组的URL
    const blobData = new Blob([rsp], { type: 'blob' })
    if (blobData instanceof Blob) {
      // 2 手动生成文件的 url
      const url = window.URL.createObjectURL(blobData)
      // 3 创建 a 标签，模拟点击事件
      const link = document.createElement('a')
      link.href = url
      // 3.1 重命名下载文件名称
      link.download = row.name
      document.body.appendChild(link)
      const evt = document.createEvent('MouseEvents')
      evt.initEvent('click', false, false)
      link.dispatchEvent(evt)
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }
  })
}
const handleSelectionChange = (val) => {
  multiItems.value = val
}
const batchDelete = () => {
  const ids = multiItems.value.map((item) => item.id)
  batchDel(ids).then((rsp) => {
    if (rsp.code === 200) {
      queryItems()
    }
  })
}

onMounted(() => {
  queryItems()
})
</script>

<style scoped>
.top {
  display: flex;
  justify-content: left;
}
</style>
